---
title: Prefer BuildContext Extensions
description: The prefer_build_context_extensions rule.
---

import { Badge } from '@astrojs/starlight/components';
import EnableRuleSnippet from '~/components/lint-rules/EnableRuleSnippet.astro';
import BadSnippet from '~/components/lint-rules/prefer_build_context_extensions/BadSnippet.mdx';
import GoodSnippet from '~/components/lint-rules/prefer_build_context_extensions/GoodSnippet.astro';

<div class="badges">
	<Badge text="new" />
	<Badge text="dart" variant="note" />
</div>

Prefer using `BuildContext` extensions to access a `Bloc` or `Repository`
instance.

:::note

This lint rule was introduced in version `0.3.2` of
[`package:bloc_lint`](https://pub.dev/packages/bloc_lint)

:::

## Rationale

For consistency, prefer using `BuildContext` extensions like `context.read`,
`context.watch`, and `context.select` instead of `BlocProvider.of`,
`RepositoryProvider.of`, `BlocBuilder` or `BlocSelector`.

| explicit method                                                     | extension             |
| ------------------------------------------------------------------- | --------------------- |
| `BlocProvider.of<Bloc>(context, listen: false)`                     | `context.read<Bloc>`  |
| `BlocBuilder<Bloc, State>(...)` or `BlocProvider.of<Bloc>(context)` | `context.watch<Bloc>` |
| `BlocSelector<Bloc, State>(...)`                                    | `context.select`      |

## Examples

**Avoid** using `BlocProvider.of<T>(context)` to access a `Bloc` instance.

**BAD**:

<BadSnippet />

**GOOD**:

<GoodSnippet />

## Enable

To enable the `prefer_build_context_extensions` rule, add it to your
`analysis_options.yaml` under `bloc` > `rules`:

<EnableRuleSnippet name="prefer_build_context_extensions" />
